package com.tanhua.server.controller;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserInfoSerivce;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserInfoSerivce userInfoSerivce;

    /**
     * 保存用户信息
     *  userinfo
     *  请求头中携带token
     */
    @PostMapping("/loginReginfo")
    public ResponseEntity loginReginfo(@RequestBody UserInfo userInfo,
                                       @RequestHeader("Authorization") String token){
        //解析token
        if (!JwtUtils.verifyToken(token)){
            return null;
        }
        Claims claims = JwtUtils.getClaims(token);
        //设置id
        Integer id = (Integer) claims.get("id");
        userInfo.setId(Long.valueOf(id));
        //调用service
        userInfoSerivce.save(userInfo);
        return null;
    }

    /**
     * 上传用户头像
     */
    @PostMapping("/loginReginfo/head")
    public ResponseEntity head(MultipartFile headPhoto, @RequestHeader("Authorization") String token) throws IOException {
        //2、向userinfo中设置用户id
        //3、调用service
        log.info("上传用户头像 image = {}",headPhoto.getSize());
        userInfoSerivce.updateHead(headPhoto, UserHolder.getUserId());
        return ResponseEntity.ok(null);
    }
}
